package com.hx.zhg.web.filter;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.util.HashSet;
import java.util.Set;

/**
 * 基础过滤器
 */
public abstract class BaseFilter implements Filter {

    /**
     * 静态资源后缀名
     */
    protected static final Set<String> STATIC_SUFFIX_LIST = new HashSet<>();
    /**
     * 静态资源后缀名分隔符
     */
    protected static final String STATIC_SUFFIX_SPLIT = ",";

    @Value("${env}")
    protected String env;
    @Value("${urlWhiteList}")
    protected String urlWhiteList;
    @Value("${serverUrl}")
    protected String serverUrl;
    @Value("${busUrlWhiteList}")
    protected String busUrlWhiteList;
    @Value("${staticSuffix}")
    protected String staticSuffix;
    @Value("${cdnUrl}")
    protected String cdnUrl;
    @Value("${resEnv}")
    protected String resEnv;
    @Value("${server.context-path}")
    protected String contextPath;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String[] staticSuffixs = staticSuffix.split(STATIC_SUFFIX_SPLIT);
        for (int i = 0; i < staticSuffixs.length; i++) {
            STATIC_SUFFIX_LIST.add(staticSuffixs[i]);
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * 判断url是否是静态文件访问
     *
     * @param requestURI
     * @param staticSuffix
     * @return
     */
    public boolean isStaticFile(String requestURI, String staticSuffix) {
        if (StringUtils.isEmpty(staticSuffix)) {
            return false;
        }
        int lastIndexDot = requestURI.lastIndexOf(".");
        if (lastIndexDot < 0) {
            return false;
        }
        String suffix = requestURI.substring(lastIndexDot + 1);
        if (StringUtils.isEmpty(suffix)) {
            return false;
        }
        // 设置用户浏览器对静态文件缓存
        if (STATIC_SUFFIX_LIST.contains(suffix)) {
            return true;
        } else {
            return false;
        }
    }

}
